/*
 * BanBu_SecondaryDialogueViewController
 * @description 本文件提对话打招呼界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提对话打招呼界面的ViewController
 */

#import "BanBu_SecondaryDialogueViewController.h"
#import "BanBu_DialogueCell.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_ChatViewController.h"
#import "TKLoadingView.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "LeveyTabBarController.h"
#import "Banbu_NopushView.h"
@interface BanBu_SecondaryDialogueViewController ()

@end

@implementation BanBu_SecondaryDialogueViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.tabBarController.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.deletDic = [NSMutableDictionary dictionaryWithCapacity:10];
    _isPush = YES;
    MyAppDataManager.secondaryDialog = self;
    
    self.title = NSLocalizedString(@"sayHi", nil);
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-88) style:UITableViewStylePlain];
    self.tableView = tableView;
    
    [self.view addSubview:tableView];
    [tableView release];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    //添加“对话”按钮，返回对话界面
    [self createBackButton];
    
    //添加“删除”按钮
    [self createEditButton];
    
    BanBu_ImageView * img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    
    //2014年11月17日13:18:54 By yinlinlin
    Banbu_NopushView *nopush = [Banbu_NopushView shareView];
    nopush.frame = CGRectMake(0, 0, 320, 50);
    [nopush setNoticeType:NoticeOpenTypeSayHi];
    self.tableView.tableHeaderView = nopush;
    
    __block Banbu_NopushView *push = nopush;
    __block BanBu_SecondaryDialogueViewController * bself = self;
    [push setDismiss:^(UIButton *btn) {
        [UIView animateWithDuration:0.3 animations:^{
            bself.tableView.tableHeaderView = nil;
        }];
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    self.sliding = YES;
    [self updateBadgeShow];
    [self.leveyTabBarController hidesTabBar:NO animated:YES];
    _isPush = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createBackButton
{
    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
    btn_return.position = ButtonPositionLeft;
    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
    //    btn_return.titleLabel.font = [UIFont systemFontOfSize:18];
    
    UIBarButtonItem *bar_itemreturn = nil;
    NSString *str = [NSString stringWithFormat:@" %@",NSLocalizedString(@"dialogueTitle", nil)];
    CGFloat btnLen = [str sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(100, 30)].width;
    
    btn_return.frame=CGRectMake(0, 0, btnLen+20, 30);
    
    [btn_return setTitle:str forState:UIControlStateNormal];
    
    bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
    
    self.navigationItem.leftBarButtonItem = bar_itemreturn;
    
    //设置气泡
    [self setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
}
-(void)createEditButton
{
    BanBu_NavButton *actionButton=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    actionButton.position = ButtonPositionRight;
    
    actionButton.frame=CGRectMake(0, 0, 40, 30);
    
    [actionButton addTarget:self action:@selector(changeList) forControlEvents:UIControlEventTouchUpInside];
    
    [actionButton setImage:[UIImage imageNamed:@"deleteDialog.png"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:actionButton]autorelease];
    [actionButton release];
}

-(void)createDeleteButton
{
    CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    deleteButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    deleteButton.position = ButtonPositionRight;
    deleteButton.frame=CGRectMake(0, 0, btnLen1 + 20, 30);
    deleteButton.tag = 101;
    [deleteButton addTarget:self action:@selector(editTable) forControlEvents:UIControlEventTouchUpInside];
    [deleteButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:deleteButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
}

-(void)editTable
{
    if (_slided)
    {
        return;
    }
    self.sliding = NO;
    [self setEditing:!self.tableView.editing animated:YES];
}

//修改tableView可编辑状态
- (void)setEditing:(BOOL)editting animated:(BOOL)animated
{
    [super setEditing:!self.editing animated:YES];
    if(self.editing)
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        
        [deleteButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    }
    else
    {
        self.sliding = YES;
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"deleteButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        
        [deleteButton setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
    }
    
    if(self.deletDic.count)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"deleteNotice", nil) activityAnimated:YES];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            NSMutableArray *tempArr = [NSMutableArray array];
            
            //删除本地数据库中该人对话及聊天记录
            [MyAppDataManager deleteTalkPeople:self.deletDic.allKeys];
            
            NSInteger total = 0;
            NSMutableArray * userIDArray = [NSMutableArray arrayWithCapacity:20];
            for(NSDictionary *aTalk in MyAppDataManager.secondaryTalkPeople)
            {
                total += [VALUE(KeyUnreadNum, aTalk) integerValue];
                
                if ([self.deletDic valueForKey:[aTalk valueForKey:KeyFromUid]])
                {
                    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[[self.deletDic valueForKey:[aTalk valueForKey:KeyFromUid]] integerValue] inSection:0];
                    
                    [userIDArray addObject:indexPath];
                    [tempArr addObject:aTalk];
                }
            }
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",total],@"pushcount",nil];
            
            //提交推送
            [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:dic delegate:self];
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                //数据源删除
                [MyAppDataManager.secondaryTalkPeople removeObjectsInArray:tempArr];
                
                if (self.firstSayHi)
                {
                    if (MyAppDataManager.secondaryTalkPeople.count)
                    {
                        //修改打招呼最后一条显示的内容
                        [MyAppDataManager setLastDialogBySayHi:[MyAppDataManager.secondaryTalkPeople objectAtIndex:0]];
                    }
                    else
                    {
                        [MyAppDataManager deleteBlackDialog:@"600"];
                    }
                }
                
                //界面删除
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:userIDArray withRowAnimation:UITableViewRowAnimationFade];
                [self.tableView endUpdates];
                
                self.firstSayHi = NO;
                [self.deletDic removeAllObjects];
                
                [self setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
                [MyAppDataManager updateUnreadNum];
                [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0.0];
            });
        });
    }
    if (!self.editing)
    {
        [self createEditButton];
    }
}


-(void)popself
{
    MyAppDataManager.secondaryDialog = nil;
    [MyAppDataManager.secondaryTalkPeople removeAllObjects];
    [self.navigationController popViewControllerAnimated:YES];
}

//更新全局对话数量及气泡数字
- (void)updateBadgeShow
{
    [MyAppDataManager readTalkPeopleByUserID:@"600"];
    
    [self setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
    
    [self.tableView reloadData];
}

//设置返回按钮的气泡
- (void)setBadgeValue:(NSString *)badgeValue withButtonIndex:(NSInteger)_index
{
    [_badgeValue release];
    _badgeValue = [badgeValue retain];
    if(!badgeValue||![badgeValue intValue])
    {
        if(self.badgeView)
        {
            self.badgeView.hidden = YES;
        }
    }
    else
    {
        float width = [badgeValue sizeWithFont:[UIFont boldSystemFontOfSize:14]].width+12;
        if(!self.badgeView)
        {
            self.badgeView = [[[UIBadgeView alloc] initWithFrame:CGRectMake(self.navigationItem.leftBarButtonItem.customView.bounds.size.width-width/3, -2, width, 20)] autorelease];
            
            self.badgeView.backgroundColor = [UIColor clearColor];
            self.badgeView.badgeColor = [UIColor redColor];
            self.badgeView.tag = _index;
            [self.navigationItem.leftBarButtonItem.customView addSubview:_badgeView];
        }
        
        self.badgeView.badgeString = badgeValue;
        self.badgeView.hidden = NO;
        [UIView animateWithDuration:0.5
                         animations:^{
                             self.badgeView.frame = CGRectMake(self.navigationItem.leftBarButtonItem.customView.bounds.size.width - width/3, -2, width, 20);
                         }];
    }
}


//要添加一个按钮“设置聊天背景”
-(void)changeList
{
    UIActionSheet *aSheet = [[UIActionSheet alloc]initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil)
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:NSLocalizedString(@"batchRemove", nil),NSLocalizedString(@"clearSayHi",nil), nil];
    //    NSLocalizedString(@"setSayHi", nil),
    aSheet.tag = 10101;
    [aSheet showInView:self.view.window];
    [aSheet release];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return MyAppDataManager.secondaryTalkPeople.count;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    BanBu_DialogueCell *cell = (BanBu_DialogueCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[BanBu_DialogueCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSDictionary *aTalk;
    if([MyAppDataManager.secondaryTalkPeople count]>indexPath.row)
    {
        aTalk = [MyAppDataManager.secondaryTalkPeople objectAtIndex:indexPath.row];
    }
    else
    {
        aTalk=nil;
    }
    [cell setAvatar:VALUE(KeyUface, aTalk)];
    [cell setName:[MyAppDataManager IsInternationalLanguage:VALUE(KeyUname, aTalk)]];
    
    [cell setLastInfo: VALUE(KeyStime, aTalk)];
    [cell setDistance:[MyAppDataManager IsInternationalLanguage:VALUE(KeyDmeter, aTalk)]];
    [cell setAge:VALUE(KeyAge, aTalk) sex:[VALUE(KeySex, aTalk) boolValue] verify:[[aTalk valueForKey:@"verify"] boolValue]];
    
    [cell setlastDialogue:VALUE(KeyLasttalk, aTalk) andType:[VALUE(KeyType, aTalk) intValue]];
    
    //加V
    [cell setVerify:![[aTalk valueForKey:@"verify"] isEqual:@"y"]];
    
    //加VIP
    [cell setVIPFlag:[[aTalk valueForKey:@"userlevel"] integerValue]>0];
    
    if(![VALUE(KeyLasttalk, aTalk) isEqualToString:@""])
    {
        if([VALUE(KeyMe, aTalk) boolValue])
        {
            if([aTalk valueForKey:@"status"])
            {
                [cell setReadAndSend:[VALUE(KeyStatus, aTalk) intValue]];
            }
        }
        else
        {
            [cell setReadAndSend:DialogueMessageStautusNoneType];
        }
        cell.receiveAndsend.hidden = NO;
        [cell setReceiveAndsend11:[VALUE(KeyMe, aTalk) boolValue]];
    }
    else
    {
        cell.receiveAndsend.hidden = YES;
        [cell setReadAndSend:DialogueMessageStautusNoneType];
    }
    
    NSInteger unReadNum = [VALUE(KeyUnreadNum, aTalk) integerValue];
    [cell setBadageValue:[NSString stringWithFormat:@"%i",unReadNum]];
    
    //多选删除
    if([MyAppDataManager.secondaryTalkPeople count]>indexPath.row)
    {
        NSMutableDictionary *talkPeopleDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.secondaryTalkPeople objectAtIndex:indexPath.row]];
        BOOL isChecked = [[talkPeopleDic valueForKey:@"isChecked"] boolValue];
        
        [cell setChecked:isChecked];
        
        NSString * indexPath = [self.deletDic valueForKey:[aTalk valueForKey:KeyFromUid]];
        
        if (indexPath)
        {
            [cell setChecked:YES];
        }
    }
    
    return cell;
}


#pragma mark - Table view delegate
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.sliding)
    {
        BanBu_DialogueCell * cell = (BanBu_DialogueCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.sliding = self.sliding;
        _slided = YES;
        return UITableViewCellEditingStyleDelete;
    }
    else
    {
        return UITableViewCellEditingStyleNone;
    }
}


- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    _slided = NO;//滑动删除结束
}

//实现删除行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    _slided = NO;//滑动删除结束
    //从数据源中删除
    NSDictionary * aTalk = [MyAppDataManager.secondaryTalkPeople objectAtIndex:indexPath.row];
    
    [MyAppDataManager deleteBlackDialog:VALUE(KeyFromUid, aTalk)];
    [MyAppDataManager.secondaryTalkPeople removeObjectAtIndex:indexPath.row];
    
    //删除table中的行
    [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //编辑状态下点击是选中或取消
    if(self.tableView.editing)
    {
        NSMutableDictionary *talkPeopleDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.secondaryTalkPeople objectAtIndex:indexPath.row]];
        BOOL isChecked = [[talkPeopleDic valueForKey:@"isChecked"] boolValue];
        
        [talkPeopleDic setValue:[NSString stringWithFormat:@"%d",!isChecked] forKey:@"isChecked"];
        
        NSString * userid = [talkPeopleDic valueForKey:KeyFromUid];
        
        [MyAppDataManager.secondaryTalkPeople replaceObjectAtIndex:indexPath.row withObject:talkPeopleDic];
        
        BanBu_DialogueCell *cell = (BanBu_DialogueCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell setChecked:!isChecked];
        if(!isChecked)
        {
            [self.deletDic setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:userid];
            if (indexPath.row == 0)
            {
                self.firstSayHi = YES;
            }
        }
        else
        {
            [self.deletDic removeObjectForKey:userid];
            if (indexPath.row == 0)
            {
                self.firstSayHi = YES;
            }
        }
    }
    else
    {
        NSDictionary *userDic = [NSDictionary dictionaryWithDictionary:[MyAppDataManager.secondaryTalkPeople objectAtIndex:indexPath.row]];
        if(_isPush)
        { //防止页面卡住时，多次点击该cell，会push多个viewcontroller
            //判断未读消息是否超过20条，因为默认只会读取20条记录
            
            if([VALUE(KeyUnreadNum, userDic) integerValue]!=0)
            {
                NSDictionary *unReadDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",0-[VALUE(KeyUnreadNum, userDic) integerValue]],@"pushcount",nil];
                
                [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:unReadDic delegate:self];
                
                //更改数据库，将这个人的未读条数清零
                [MyAppDataManager setUnreadNumber:0 With:[userDic valueForKey:@"userid"]];
                
                //更新顶级目录的unReadNum
                [MyAppDataManager updateSayHiUnReadNum];
                [MyAppDataManager.readedUserArray addObject:[userDic valueForKey:KeyFromUid]];
            }
            
            NSInteger unReadNum = [VALUE(KeyUnreadNum, userDic) integerValue];
            
            //发送已读状态
            if (AppComManager.netStatus!= NotReachable)
            {
                if (MyAppDataManager.readedUserArray.count > 2)
                {
                    [MyAppDataManager sendReadedStatus:MyAppDataManager.readedUserArray];
                    [MyAppDataManager.readedUserArray removeAllObjects];
                }
            }
            
            if(unReadNum>5)
            {
                if (unReadNum<100)
                {
                    [MyAppDataManager readTalkList:[userDic valueForKey:@"userid"] WithNumber:[VALUE(KeyUnreadNum, userDic) integerValue]];
                }
                else
                {
                    [MyAppDataManager readTalkList:[userDic valueForKey:@"userid"] WithNumber:100];
                }
            }
            else
            {
                [MyAppDataManager readTalkList:[userDic valueForKey:@"userid"] WithNumber:5];
            }
            
            //彩蛋处理
            BOOL showEggs = NO;
            
            NSString * content = nil;
            
            
            if (unReadNum > 5)
            {
                for (NSDictionary * amsg in MyAppDataManager.dialogs)
                {
                    if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeText  && ![[amsg valueForKey:KeyShowFrom] isEqualToString:@"snap"])
                    {
                        NSArray * array = [MyAppDataManager easteregg:VALUE(KeyContent, amsg)];
                        if (array)
                        {
                            showEggs = YES;
                            content = [amsg valueForKey:KeyContent];
                            break;
                        }
                    }
                }
            }
            else
            {
                //unReadNum为1；count：5
                for (int i = MyAppDataManager.dialogs.count -1; i >= MyAppDataManager.dialogs.count - unReadNum && i>=0; i--)
                {
                    NSDictionary * amsg = [MyAppDataManager.dialogs objectAtIndex:i];
                    
                    if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeText && ![[amsg valueForKey:KeyShowFrom] isEqualToString:@"snap"])
                    {
                        NSArray * array = [MyAppDataManager easteregg:VALUE(KeyContent, amsg)];
                        if (array)
                        {
                            showEggs = YES;
                            content = [amsg valueForKey:KeyContent];
                            break;
                        }
                    }
                }
            }
            
            
            BanBu_ChatViewController *chat = [[BanBu_ChatViewController alloc] initWithPeopleProfile:userDic];
            
            //是否显示headerview
            if([[userDic valueForKey:@"userid"] intValue]<1000)
            {
                chat.hidHeader = YES;
            }
            else
            {
                chat.hidHeader = NO;
            }
            _isPush = NO;
            
            chat.returnBtTitle = @"sayHi";//设置聊天界面返回按钮显示为“对话”
            
            chat.smileViewBackup = MyAppDataManager.smileViewBackup;
            chat.content = content;
            
            if (indexPath.row ==0)
            {
                chat.firstSayHi = YES;
            }
            [self.navigationController pushViewController:chat animated:YES];
            [chat release];
        }
    }
}

#pragma mark - actionDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0://批量删除
        {
            self.sliding = NO;
            [self createDeleteButton];
            [self editTable];
        }
            break;
        case 1://清空全部
        {
            [MyAppDataManager clearAllSecondaryUserMsg:@"600" andUserArray:MyAppDataManager.secondaryTalkPeople];
            [MyAppDataManager.secondaryTalkPeople removeAllObjects];
            [MyAppDataManager deleteBlackDialog:@"600"];
            [self setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
            [MyAppDataManager updateUnreadNum];
            [self.tableView reloadData];
        }
            break;
        default:
            break;
    }
}

-(void)dealloc
{
    [AppComManager cancalHandlesForObject:self];
    [_badgeValue release],_badgeValue = nil;
    [_badgeView release],_badgeView = nil;
    [_deletDic release],_deletDic = nil;
    MyAppDataManager.secondaryDialog = nil;
    self.tableView = nil;
    [super dealloc];
}
@end
